define(backboneCommon.getViewDefine("adspace.detail"), function ($,require,Collection,tpl) {
    var backboneView= Backbone.View.extend({
        el: "#container_body",
        events: {
            "click #btn_submitAdSpace": "saveSubmit"
        },
        initialize: function () {
            this.modelAttach={};
            this.modelAttach.baseData=this.model.get("modelBaseData");
            this.modelAttach.media=this.model.get("modelMedia");
            this.modelAttach.template=this.model.get("modelTemplate");
            this.listenTo(this.modelAttach.baseData, 'bind:AdFormat', this.bindAdFormat);
            this.listenTo(this.modelAttach.baseData, 'bind:Ratio', this.bindRatio);
            this.listenTo(this.modelAttach.baseData, 'bind:ImageType', this.bindImageType);
            this.listenTo(this.modelAttach.media, 'bind:DropDownMedia', this.bindMedia);
            this.listenTo(this.modelAttach.template, 'bind:DropDownTemplate', this.bindTemplate);
            this.listenTo(this.model, 'bind:Info', this.bindInfo);
            this.listenTo(this.model, 'save:Info', this.saveInfoCallback);
            this.render();
        },
        render:function(json){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml(json));
        },
        initMain:function(id){
            this.elementModel={};
            this.extObject={};
            this.pageData={};
            this.pageData.operateStatus=this.model.get("defListStatus");
            this.elementModel.form=$("#form_detailAdSpace");

        },
        bindInfo:function(){
            var self=this;
            var result=this.model.get("dataInfo");
            self.isAdd=result.isAdd;
            $(".page-operate-title").text($.ExtCommon.getStringConnect("{0}广告位",self.isAdd?"新建":"编辑"));
            if (result.res.success) {
                self.extObject.formValue=self.elementModel.form.ExtFormValue({defaultvalue:result.res.data,
                    initCallback:function(dataJson){
                        self._changeAdFormat(dataJson.adFormat);
                        self.collection.initDetailAfter(dataJson);
                        if(!$.ExtCommon.isCheckEmpty(dataJson.media)){
                            self.collection.getTemplateList({media:dataJson.media,template:dataJson.template})
                        }
                        self._bindStatus();
                        self._initTemplate();
                        self._bindInteractions();
                        self._bindBuyType();
                        $("#txt_chargePrice").ExtNumeric();
                        $(".status-disabled").prop("disabled", !self.isAdd &&dataJson.status.toString()=="1");
                        self._bindChargeType();
                        self.elementModel.form.ExtParsley();
                    }
                });
            }else{
                $.ExtNotify.error("该订单详情数据获取失败：" +result.res.msg);
            }
        },
        _bindStatus:function () {
            var list=$.ExtCommon.convertListByPara(this.pageData.operateStatus);
            this.extObject.status=$("#panel_status").ExtRadioCheckbox({type: "radio",attrName:"status",defaultInfo:{width:90},data:list});
        },
        bindAdFormat:function () {
            var self=this;
            var res=this.modelAttach.baseData.get("dataListAdFormat");
            $("#ddl_adformat").ExtSelect2({placeholder:"-请选择-", infoExt:{initindex:0,data:res.data,
                initCallback:function(list,value){
                    //self.bindRatio(value)
                },
                changeCallback:function(value){
                    self._changeAdFormat(value);
                    if(value!="5"){
                        var ratiolist=self.pageData.groupRatio[value];
                        self.elementModel.ratio.replaceData(ratiolist,-1);
                    }else{
                        self.extObject.template.init("")
                    }
                }
            }});
            if(!res.success){ $.ExtNotify.error("广告形式数据获取失败："+res.msg);}
        },
        _changeAdFormat:function(adformat){
            if(adformat=="5"){
                $("#panel_template").show();
                $("#panel_ratio").hide();
                $("#ddl_template").attr("required","");
                $("#ddl_ratio").removeAttr("required");
            }else{
                $("#panel_template").hide();
                $("#panel_ratio").show();
                $("#ddl_template").removeAttr("required");
                $("#ddl_ratio").attr("required","");
            }
        },
        bindMedia:function () {
            var self=this;
            var res=this.modelAttach.media.get("dataDropDownMedia");
            $("#ddl_media").ExtSelect2({placeholder:"-请选择-",minimumResultsForSearch: 1, infoExt:{data:res.data,
                changeCallback:function(value){
                    var listTemplate=self.pageData.groupTemplate[value];
                    if(listTemplate){
                        self.extObject.template.replaceData(listTemplate,-1);
                    }else {
                        self.collection.getTemplateList({media:value});
                    }
                }
            }});
            if(!res.success){ $.ExtNotify.error("媒体系统数据获取失败："+res.msg);}
        },
        bindRatio:function(){
            var res=this.modelAttach.baseData.get("dataListRatio");
            var adformat=$("#ddl_adformat").val();
            this.pageData.groupRatio=$.ExtCommon.getJsonByGroup(res.data, "formatId");
            var list=this.pageData.groupRatio[adformat];
            this.elementModel.ratio= $("#ddl_ratio").ExtSelect2({placeholder:"-请选择-", infoExt:{data:list}});
        },
        bindTemplate:function () {
            var result=this.modelAttach.template.get("dataDropDownTemplate");
            var list=result.res.success?result.res.data:[];
            this.pageData.groupTemplate[result.req.media.toString()]=list;
            this.extObject.template.replaceData(list,$.ExtCommon.isCheckEmpty(result.req.template.toString())?-1:result.req.template.toString());
            if(!result.res.success){ $.ExtNotify.error("广告形式数据获取失败："+res.msg);}
        },
        _initTemplate:function(){
            var self=this;
            self.pageData.groupTemplate=[];
            self.extObject.template = $("#ddl_template").ExtSelect2({placeholder: "-请选择-", infoExt: {data:[],
                clickCallback:function(listdata){
                    var errmsg= $.ExtCommon.isCheckEmpty(listdata)?($.ExtCommon.isCheckEmpty($("#ddl_media").val())?"注意：请先选择媒体后再选择模板":"注意：该媒体无模板数据"):"";
                    if(errmsg.length>0){$.ExtNotify.warning(errmsg);}
                }
            }});
        },
        _bindInteractions:function(){
            var self=this;
            var list=this.model.get("defListInteractions");
            self.extObject.interactions=$("#panel_interactions").ExtRadioCheckbox({type: "checkbox",attrName:"interactions",defaultInfo:{width:90}, data:list,
                initCallback: function() {
                    if(self.isAdd){
                        self.extObject.interactions.setAll()
                    }else{
                        if(self.extObject.status.getValue()=="1"){
                            self.extObject.interactions.disabledAll();
                        }
                    }
                }
            });
        },
        bindImageType:function(){
            var self=this;
            var res=self.modelAttach.baseData.get("dataListImageType");
            var list=$.ExtCommon.convertListByPara(res.data,{"id":"name"});
            self.extObject.imageType=$("#panel_imageType").ExtRadioCheckbox({type: "checkbox",attrName:"imageType",defaultInfo:{width:90}, data:list,
                initCallback: function() {
                    if(self.isAdd){
                        self.extObject.imageType.setAll()
                    }else{
                        if(self.extObject.status.getValue()=="1"){
                            self.extObject.imageType.disabledAll();
                        }
                    }
                }
            });
        },
        _bindBuyType:function () {
            var list=$.ExtCommon.convertListByPara(this.model.get("defListBuyType"));
            $("#ddl_buyType").ExtSelect2({placeholder:"-请选择-",allowClear: true,infoExt:{data:list}});
        },
        _bindChargeType:function () {
            var self=this;
            var list=$.ExtCommon.convertListByPara(this.model.get("defListChargeType"));
            $("#ddl_chargeType").ExtSelect2({placeholder:"-请选择-",allowClear: true, infoExt:{data: list,
                initCallback:function (list,value) {
                    self._changeChargeType(value);
                },
                changeCallback:function(value){
                    $("#txt_chargePrice").val("");
                    self._changeChargeType(value);

                    self.elementModel.form.ExtParsley().validate("#txt_chargePrice");
                }
            }});
        },
        _changeChargeType:function(chargeType){
            var elementPrice=$("#txt_chargePrice");
            var option={mDec:2};
            if(chargeType=="3"){
                elementPrice.data("vMax",100).attr("data-parsley-max-greater",100);
                $("#span_chargeTypeName").text("%");
                option.vMax=100.00;
            }else{
                elementPrice.data("v-max",99999999.99).removeAttr("data-parsley-max-greater");
                $("#span_chargeTypeName").text("元");
                option.vMax=99999999.99;
            }
            elementPrice.ExtNumeric().refresh(option);
        },
        _checkFrom:function () {
            $.ExtNotify.destroy();
            var isExtCheck=true;
            var info= this.elementModel.form.ExtFormValue("getValues");
            if($.ExtCommon.isCheckEmpty(info.imageType)){
                isExtCheck=false;
                $.ExtNotify.error("请选择图片格式");
            }
            if($.ExtCommon.isCheckEmpty(info.interactions)){
                isExtCheck=false;
                $.ExtNotify.error("请选择互动设置");
            }
            this._changeAdFormat(info.adformat);
            this._changeChargeType(info.chargeType);
            return this.elementModel.form.ExtParsley("validate") && isExtCheck;
        },
        saveSubmit:function(){
            if (this._checkFrom()) {
                var infoOriginal = this.elementModel.form.ExtFormValue("getOriginalData");
                var ajaxdata = this.elementModel.form.ExtFormValue("getValues");
                if(infoOriginal.id){ajaxdata.id=infoOriginal.id}
                this.collection.saveInfo(ajaxdata);
            }
        },
        saveInfoCallback: function () {
            var self=this;
            var result=this.model.get("dataSave");
            if (result.res.success) {
                $.ExtNotify.success("保存成功!");
                $.ExtAssist.goUrlHref("#adspace");
            }else{
                $.ExtNotify.error(result.res.msg);
            }
        }
    });
    var viewModel=function(param){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({collection:this.collection,model:this.model});
        var id=param?param[0]:null;
        this.view.initMain(id);
    };
    viewModel.prototype={};
    return viewModel;
});